//
//  JParser.m
//  MobileGuide
//
//  Created by 鞠 文杰 on 14-5-12.
//  Copyright (c) 2014年 CSICS. All rights reserved.
//

#import "DOQuery.h"
#import "DOObjects.h"


@interface DOQuery (){
    NSOperationQueue *queue;
    Class modelClazz;
}

@end

@implementation DOQuery
@synthesize url;

- (id)initWithClassName:(NSString *)classname
                    url:(NSString *)theUrl
{
    self = [super init];
    if (self) {
        url = theUrl;
        
        modelClazz = objc_getClass([classname UTF8String]);
        if (!modelClazz) {
            @throw [NSString stringWithFormat:@"没有找到类名为 %@ 的类",classname];
        }
		queue = [[NSOperationQueue alloc] init];
    }
    return self;
}


- (void)fetchDataInBackground:(DOArrayResultBlock)block
{
    NSString *url1 = url;
    url1 = [url1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url1] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:kDOParseTimeOut];
    [NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
		//如果没有错误
        if (!connectionError) {
            
            //待添加response statuscode判断
            
            if ([modelClazz isSubclassOfClass:[DOObjects class]]) {
                NSError *error;
                id JObjc = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                
                
                if (!error) {
                    // ======================
                    // 提取数据
                    // ======================
                    NSArray *dataBody ;
                    //如果有自定义的抽取数据方法
                    if (self.extractMethod) {
                        self.extractMethod(JObjc,&dataBody);
                    }else{
                        //默认解析数据类型
                        //{'result':[{...}]}
                        id tmpResult = [JObjc objectForKey:@"result"];
                        if ([tmpResult isKindOfClass:[NSArray class]]) {
                            dataBody = tmpResult;
                        }else{
                            dataBody = [NSArray array];
                        }
                    }
                    // ======================
                    // 提取数据 结束
                    // ======================
                    
                    block([modelClazz jsonObjToModel:dataBody],nil);
                }else{
                    block(nil,error);
                }
                
            }else{
                //不支持没有继承自baseModel的类
                NSError *err = [[NSError alloc] initWithDomain:kDOParseErrorDomain code:kDOParseInvalidInstanceError userInfo:@{@"error":@"不支持没有继承自BaseModel的类"}];
                block(nil,err);
            }
        }else{
            block(nil,connectionError);
        }
    }];
}

- (void)fetchDataInBackgroundWithURL:(NSString *)theUrl block:(DOBooleanResultBlock)block
{
    NSString *url1 = theUrl;
    url1 = [url1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url1] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:kDOParseTimeOut];
    [NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
		//如果没有错误
        if (!connectionError) {

        }else{
            
        }
    }];
    
}

@end
